<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="姓名" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入姓名" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="身份证号" v-bind="validateInfos.idnumber">
            <a-input v-model:value="formData.idnumber" placeholder="请输入身份证号" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="审核状态" v-bind="validateInfos.status">
            <a-select v-model:value="formData.status" placeholder="请选择审核状态" :disabled="disabled">
              <a-select-option :value="0">未提交审核</a-select-option>
              <a-select-option :value="1">审核中</a-select-option>
              <a-select-option :value="2">通过审核</a-select-option>
              <a-select-option :value="3">未通过审核</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="性别" v-bind="validateInfos.gender">
            <a-select v-model:value="formData.gender" placeholder="请选择性别" :disabled="disabled">
              <a-select-option :value="1">男</a-select-option>
              <a-select-option :value="2">女</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="年龄" v-bind="validateInfos.age">
            <a-input-number v-model:value="formData.age" placeholder="请输入年龄" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="手机号" v-bind="validateInfos.phone">
            <a-input v-model:value="formData.phone" placeholder="请输入手机号" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="邮箱" v-bind="validateInfos.email">
            <a-input v-model:value="formData.email" placeholder="请输入邮箱" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="医院" v-bind="validateInfos.hospital">
            <a-select
              v-model:value="formData.hospital"
              placeholder="请选择医院"
              :disabled="disabled"
              :options="hospitalOptions"
              :field-names="{ label: 'label', value: 'value' }"
              show-search
              :filter-option="filterHospitalOption"
              @change="handleHospitalChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="医院名称" v-bind="validateInfos.hospitalname">
            <a-input v-model:value="formData.hospitalname" placeholder="选择医院后自动填充" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="项目组" v-bind="validateInfos.projectid">
            <a-tree-select
              v-model:value="formData.projectid"
              :tree-data="projectTreeData"
              :field-names="{ label: 'title', value: 'value', children: 'children' }"
              :disabled="!formData.hospital || disabled"
              :placeholder="formData.hospital ? '请选择项目组' : '请先选择医院'"
              show-search
              tree-node-filter-prop="title"
              @change="handleProjectChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="项目组名称" v-bind="validateInfos.projectname">
            <a-input v-model:value="formData.projectname" placeholder="选择项目组后自动填充" :disabled="true" />
          </a-form-item>
        </a-col>
        <!-- 专业字段隐藏 -->
        <!-- <a-col :span="24">
          <a-form-item label="专业" v-bind="validateInfos.major">
            <a-input v-model:value="formData.major" placeholder="请输入专业" :disabled="disabled" />
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="学历" v-bind="validateInfos.education">
            <a-input v-model:value="formData.education" placeholder="请输入学历" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="职业" v-bind="validateInfos.profession">
            <a-input v-model:value="formData.profession" placeholder="请输入职业" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="职称" v-bind="validateInfos.title">
            <a-input v-model:value="formData.title" placeholder="请输入职称" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="职位" v-bind="validateInfos.position">
            <a-input v-model:value="formData.position" placeholder="请输入职位" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="工作年限" v-bind="validateInfos.workyears">
            <a-input-number v-model:value="formData.workyears" placeholder="请输入工作年限" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="执业证编号" v-bind="validateInfos.licensenumber">
            <a-input v-model:value="formData.licensenumber" placeholder="请输入执业证编号" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="资格证编号" v-bind="validateInfos.qualificationnumber">
            <a-input v-model:value="formData.qualificationnumber" placeholder="请输入资格证编号" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="证书获取时间" v-bind="validateInfos.certificatetime">
            <a-input v-model:value="formData.certificatetime" placeholder="请输入证书获取时间" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否为专家" v-bind="validateInfos.isspecialty">
            <a-input v-model:value="formData.isspecialty" placeholder="请输入是否为专家" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否为教师" v-bind="validateInfos.isteacher">
            <a-input v-model:value="formData.isteacher" placeholder="请输入是否为教师" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="级别" v-bind="validateInfos.level">
            <a-input v-model:value="formData.level" placeholder="请输入级别" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="培训经历" v-bind="validateInfos.training">
            <a-textarea v-model:value="formData.training" :rows="4" placeholder="请输入培训经历" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="技术特长" v-bind="validateInfos.skills">
            <a-input v-model:value="formData.skills" placeholder="请输入技术特长" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="个人简介" v-bind="validateInfos.introduction">
            <a-textarea v-model:value="formData.introduction" :rows="4" placeholder="请输入个人简介" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="地址" v-bind="validateInfos.address">
            <a-input v-model:value="formData.address" placeholder="请输入地址" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="证书编号" v-bind="validateInfos.certificatenumber">
            <a-input v-model:value="formData.certificatenumber" placeholder="请输入证书编号" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="银行卡号码" v-bind="validateInfos.bankcard">
            <a-input v-model:value="formData.bankcard" placeholder="请输入银行卡号码" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同编码" v-bind="validateInfos.contractcode">
            <a-input v-model:value="formData.contractcode" placeholder="请输入合同编码" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否通过考试" v-bind="validateInfos.passexam">
            <a-select v-model:value="formData.passexam" placeholder="请选择是否通过考试" :disabled="passexamDisabled">
              <a-select-option :value="'1'">是</a-select-option>
              <a-select-option :value="'0'">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否已签署" v-bind="validateInfos.issign">
            <a-select v-model:value="formData.issign" placeholder="是否已签署" :disabled="true">
              <a-select-option :value="'1'">是</a-select-option>
              <a-select-option :value="'0'">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, getDepartName, queryAllTreeListByPid } from '../NurseuserProfile.api';
  import { Form } from 'ant-design-vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useRoute } from 'vue-router';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formBpm: { type: Boolean, default: true },
  });

  const route = useRoute();

  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    name: '',
    idnumber: '',
    status: undefined,
    gender: undefined,
    age: undefined,
    phone: '',
    email: '',
    hospital: '',
    hospitalname: '',
    projectid: '',
    projectname: '',
    major: '',
    education: '',
    profession: '',
    title: '',
    position: '',
    workyears: undefined,
    licensenumber: '',
    qualificationnumber: '',
    certificatetime: '',
    isspecialty: '',
    isteacher: '',
    level: '',
    training: '',
    photo: '',
    skills: '',
    introduction: '',
    address: '',
    certificatenumber: '',
    bankcard: '',
    openid: '',
    unionid: '',
    contractcode: '',
    passexam: '',
    issign: '',
  });

  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const projectTreeData = ref<any[]>([]);
  const hospitalOptions = ref<any[]>([]);

  //表单验证
  const validatorRules = {
    name: [{ required: true, message: '请输入姓名!' }],
    idnumber: [{ required: true, message: '请输入身份证号!' }],
    gender: [{ required: true, message: '请选择性别!' }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 医院选项搜索过滤
  function filterHospitalOption(input, option) {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  }

  // 加载医院选项（获取完整的医院数据，包括 sysOrgCode）
  async function loadHospitalOptions() {
    try {
      const result = await defHttp.get({
        url: '/nurse_hospital/nurseHospital/rootList',
        params: {
          pageNo: 1,
          pageSize: 9999,
        },
      });
      if (result && result.records && Array.isArray(result.records)) {
        hospitalOptions.value = result.records.map((item) => ({
          value: item.id,
          label: item.name,
          text: item.name,
          sysOrgCode: item.sysOrgCode,
        }));
      }
    } catch (error) {
      console.error('加载医院选项失败:', error);
    }
  }

  // 医院选择改变事件
  async function handleHospitalChange(value) {
    const hospital = hospitalOptions.value.find((item) => item.value === value);

    if (hospital) {
      formData.hospitalname = hospital.text || hospital.label;
    }

    // 清空项目组
    formData.projectid = '';
    formData.projectname = '';
    projectTreeData.value = [];

    // 加载项目组数据 - 根据医院的 sys_org_code 查询
    if (value && hospital && hospital.sysOrgCode) {
      try {
        const departResult = await getDepartName({ orgCode: hospital.sysOrgCode });

        if (departResult && departResult.id) {
          const treeResult = await queryAllTreeListByPid({ pid: departResult.id });

          if (treeResult && Array.isArray(treeResult)) {
            projectTreeData.value = convertToTreeData(treeResult);
          }
        }
      } catch (error) {
        console.error('加载项目组数据失败:', error);
      }
    }
  }

  // 转换部门数据为树形选择器格式
  function convertToTreeData(data) {
    if (!Array.isArray(data)) return [];

    return data.map((item) => {
      const nodeId = item.id || item.key || item.value;
      const nodeTitle = item.departName || item.name || item.title || item.label;

      return {
        title: nodeTitle,
        key: nodeId,
        value: nodeId,
        children: item.children && item.children.length > 0 ? convertToTreeData(item.children) : undefined,
      };
    });
  }

  // 项目组选择改变事件
  function handleProjectChange(value, label, extra) {
    const findNode = (nodes, targetKey) => {
      for (const node of nodes) {
        if (node.key === targetKey) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = findNode(node.children, targetKey);
          if (found) return found;
        }
      }
      return null;
    };

    const selectedNode = findNode(projectTreeData.value, value);
    if (selectedNode) {
      formData.projectname = selectedNode.title;
    } else if (Array.isArray(label) && label.length > 0) {
      formData.projectname = label[label.length - 1];
    } else if (typeof label === 'string') {
      formData.projectname = label;
    }
  }

  // 表单禁用
  const disabled = computed(() => {
    return props.formDisabled;
  });

  // 是否通过考试字段的禁用状态：只有 type=1 时可以编辑
  const passexamDisabled = computed(() => {
    // 如果整体表单禁用，则禁用
    if (props.formDisabled) {
      return true;
    }
    // 如果 URL 参数中有 type=1，则可以编辑（返回 false 表示不禁用）
    // 否则不可编辑（返回 true 表示禁用）
    return route.query.type !== '1';
  });

  /**
   * 新增
   */
  async function add() {
    await loadHospitalOptions();
    await edit({});
  }

  /**
   * 编辑
   */
  async function edit(record) {
    await loadHospitalOptions();

    await nextTick(async () => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });

      Object.assign(formData, tmpData);

      // 如果有医院ID，加载项目组数据
      if (formData.hospital) {
        await nextTick();

        const hospital = hospitalOptions.value.find((item) => item.value === formData.hospital);

        if (hospital && hospital.sysOrgCode) {
          try {
            const departResult = await getDepartName({ orgCode: hospital.sysOrgCode });

            if (departResult && departResult.id) {
              const treeResult = await queryAllTreeListByPid({ pid: departResult.id });

              if (treeResult && Array.isArray(treeResult)) {
                projectTreeData.value = convertToTreeData(treeResult);
              }
            }
          } catch (error) {
            console.error('编辑时加载项目组数据失败:', error);
          }
        }
      }
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    let model = { ...formData };

    if (model.id) {
      isUpdate.value = true;
    }

    // 移除 issign 字段，不保存
    delete model.issign;

    // 循环数据处理数组类型
    for (let data in model) {
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value?.getProps, data);
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }

    await saveOrUpdate(model, isUpdate.value)
      .then(() => {
        emit('ok');
        resetFields();
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>

